package meijuli.com.join51.business.aliyun;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import meijuli.com.join51.business.app.MApplication;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.utils.DensityUtil;
import meijuli.com.join51.business.utils.FixXiaomiPermissionUtils;
import com.jhx.common.utils.ToastUtil;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ImageUtils {
    // 截图图片大小px
    public static final int CROP_IMAGE_SIZE = 300;
    private final static String TAG = ImageUtils.class.getSimpleName();
    public static String TEMP_PHOTO_FILE_NAME;

    private static volatile ImageUtils sImageUtils;
    private String mCurrentPhotoPath;
    private File mImageFile;

    public static ImageUtils get() {
        if (sImageUtils == null) {
            synchronized (ImageUtils.class) {
                if (sImageUtils == null) {
                    sImageUtils = new ImageUtils();
                }
            }
        }
        return sImageUtils;
    }


    public File createImageFile() throws IOException {
        @SuppressLint("SimpleDateFormat")
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = MApplication.Companion.get()
                .getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        mImageFile = File.createTempFile(imageFileName, ".jpg", storageDir);

        mCurrentPhotoPath = mImageFile.getAbsolutePath();
        return mImageFile;
    }

    public File getImageFile() {
        return mImageFile;
    }

    public void capturePhoto(Fragment fragment, int requestCode) {
        Activity activity = fragment.getActivity();
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (activity != null) {
            // 解决小米自带管理权限关闭相机权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                    && FixXiaomiPermissionUtils.isAppRefusePermission(activity)) {
                return;
            }

            if (takePictureIntent.resolveActivity(activity.getPackageManager()) != null) {
                File photoFile = null;

                try {
                    photoFile = createImageFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (photoFile != null) {
                    Uri photoURI = FileProvider.getUriForFile(fragment.getActivity(),
                            "com.join51.juhuixia.business.fileProvider",
                            photoFile);
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                }
                // 添加这一句表示对目标应用临时授权该Uri所代表的文件
                takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                fragment.startActivityForResult(takePictureIntent, requestCode);
            }
        }
    }

    /**
     * 打开相册并回调
     */
    public void openGalleryForResult(Fragment activity, int requestCode) {
        if (null == activity || null == activity.getActivity()) {
            return;
        }
        PackageManager pm = activity.getActivity().getPackageManager();
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        if (photoPickerIntent.resolveActivity(pm) != null) {
            activity.startActivityForResult(photoPickerIntent, requestCode);
        }
    }

    public void galleryImage(Fragment fragment, Uri uri, SelectImageListener listener) {
        try {
            if (null != fragment && null != fragment.getActivity() && null != uri) {
                InputStream inputStream = fragment.getActivity().getContentResolver().openInputStream(uri);
                File file = createImageFile();
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                copyStream(inputStream, fileOutputStream);
                fileOutputStream.close();
                if (inputStream != null) {
                    inputStream.close();
                }
                listener.onSelectDone();
            } else {
                ToastUtil.getInstance().showToast(MApplication.Companion.get()
                        .getString(R.string.image_format_fail));
            }
        } catch (Exception e) {
            Log.e(TAG, "Error while creating temp file", e);
            if (null != listener) {
                listener.onSelectFail();
            }
        }
    }

    /**
     * 设置动态头部大图
     */
    public static void setDynamicHeaderImage(ImageView image) {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(DensityUtil.getScreenSize().getWidth(), DensityUtil.getScreenSize().getWidth() / 3 * 2);
        image.setLayoutParams(params);
    }

    public static ImageSize setImageSize(int width, int height) {
        return new ImageSize(width, height);
    }

    /**
     * 获取相机拍照绝对路径
     */
    public static String getCaptureImageAbsolutePath(Context context, Uri uri) {
        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
        String imagePath = null;
        if (cursor != null && cursor.moveToFirst()) {
            imagePath = "file:///" + cursor.getString(cursor.getColumnIndex("_data"));// 获取绝对路径
            cursor.close();
        }
        return imagePath;
    }

    /**
     * 获取指定大小图片(根据阿里云图片服务器说明)
     *
     * @param width   宽度
     * @param height  高度
     * @param quality 图片质量
     * @return
     */
    public static String getSpecifiedSizeImageUrl(String url, int width, int height, int quality) {
        return url + "@" + width + "w_" + height + "h_" + quality + "q_1e_1x_1o.jpg";
    }

    public static String getSpecifiedSizeImageUrl(String url, int size) {
        return url + "@" + size + "w_" + size + "h_100q_1e_1x_1o.jpg";
    }

    /**
     * 初始化IamgeLoader
     *
     * @param drawableId     默认图片id
     * @param failDrawableId 加载失败显示图片的id
     * @param cacheOnDisk    是否缓存在硬盘
     * @param cacheInMemory  是否缓存在内存
     */
    public static DisplayImageOptions initImageLoader(int drawableId, int failDrawableId, boolean cacheOnDisk, boolean cacheInMemory) {
        DisplayImageOptions.Builder builder = new DisplayImageOptions.Builder();
        if (drawableId != 0) {
            builder.showImageForEmptyUri(drawableId);
        }
        if (failDrawableId != 0) {
            builder.showImageOnFail(failDrawableId);
        }
        builder.resetViewBeforeLoading(true).cacheOnDisk(cacheOnDisk).cacheInMemory(cacheInMemory).imageScaleType(ImageScaleType.EXACTLY).bitmapConfig(Bitmap.Config.RGB_565).considerExifParams(false).displayer(new FadeInBitmapDisplayer(300));
        return builder.build();
    }

    /**
     * 初始化IamgeLoader
     *
     * @param drawableId     默认图片id
     * @param failDrawableId 加载失败显示图片的id
     * @param cacheOnDisk    是否缓存在硬盘
     * @param cacheInMemory  是否缓存在内存
     */
    public static DisplayImageOptions initImageLoader(int drawableId, int failDrawableId, boolean cacheOnDisk, boolean cacheInMemory, int displayer) {
        DisplayImageOptions.Builder builder = new DisplayImageOptions.Builder();
        if (drawableId != 0) {
            builder.showImageForEmptyUri(drawableId);
        }
        if (failDrawableId != 0) {
            builder.showImageOnFail(failDrawableId);
        }
        builder.resetViewBeforeLoading(true).cacheOnDisk(cacheOnDisk).cacheInMemory(cacheInMemory).imageScaleType(ImageScaleType.EXACTLY).bitmapConfig(Bitmap.Config.RGB_565).considerExifParams(false).displayer(new FadeInBitmapDisplayer(displayer));
        return builder.build();
    }

    /**
     * 获取手机相册中的图片
     */
    public static List<String> getAlumbImages(Context context) {
        //获取相册图片，按照时间排序
        List<String> imagePaths = new ArrayList<String>();
        ContentResolver resolver = context.getContentResolver();
        Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        String[] projection = new String[]{MediaStore.Images.ImageColumns.MIME_TYPE, MediaStore.Images.ImageColumns.DATA};
        // 按时间排序
        String order = MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC";
        Cursor cursor = resolver.query(uri, projection, null, null, order);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
                if (!TextUtils.isEmpty(path)) {
                    imagePaths.add(path);
                }
            }
            cursor.close();
        }
        return imagePaths;
    }

    /**
     * 将相册中的图片uri转换路径
     */
    public static List<String> uri2Path(List<String> alumbImageList) {
        List<String> pathList = new ArrayList<String>();
        for (String uri : alumbImageList) {
            String imagePath = new String("file:/" + uri);
            pathList.add(imagePath);
        }
        return pathList;
    }


    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void copyStream(InputStream input, OutputStream output) throws IOException {
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = input.read(buffer)) != -1) {
            output.write(buffer, 0, bytesRead);
        }
    }

    /**
     * 获取图片路径
     *
     * @param context
     * @return
     */
    public static List<String> getImagePaths(Context context) {
        List<String> imagePaths = new ArrayList<String>();
        ContentResolver resolver = context.getContentResolver();
        Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        String[] projection = new String[]{MediaStore.Images.ImageColumns.MIME_TYPE, MediaStore.Images.ImageColumns.DATA};
        String order = MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC"; // 按时间排序
        Cursor cursor = resolver.query(uri, projection, null, null, order);
        //        Log.e("ImageUtil", "count = " + cursor.getCount());
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
                if (path != null) {
                    imagePaths.add(path);
                }
            }
            cursor.close();
        }
        return imagePaths;
    }

    /**
     * 获取图片路径，封装成需要的Bean对象
     *
     * @param context
     * @param selectedList 已经选中的图片
     * @return
     */
    public static List<ImageBean> getImagePaths(Context context, List<String> selectedList) {
        List<ImageBean> imagePaths = new ArrayList<ImageBean>();
        ContentResolver resolver = context.getContentResolver();
        Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        String[] projection = new String[]{MediaStore.Images.ImageColumns.MIME_TYPE, MediaStore.Images.ImageColumns.DATA};
        String order = MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC"; // 按时间排序
        Cursor cursor = resolver.query(uri, projection, null, null, order);
        //        Log.e("ImageUtil", "count = " + cursor.getCount());
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
                if (path != null) {
                    ImageBean imageBean = new ImageBean();
                    imageBean.setUrl(path);
                    imagePaths.add(imageBean);
                    imageBean.setChecked(false);
                    setCheckBoxStatus(imageBean, selectedList);
                }
            }
            cursor.close();
        }
        return imagePaths;
    }


    /**
     * 设置checkbox状态
     */
    public static void setCheckBoxStatus(ImageBean imageBean, List<String> selectedList) {
        if (selectedList != null && selectedList.size() > 0) {
            for (int i = 0; i < selectedList.size(); i++) {
                if (imageBean.getUrl().equals(selectedList.get(i))) {
                    imageBean.setChecked(true);
                    return;
                }
                imageBean.setChecked(false);
            }
        } else {
            imageBean.setChecked(false);
        }
    }

    //    /**
//     * 设置朋友圈图片大小
//     */
//    public static int getDynamicGridImageSize(Context context) {
//        int screenWid = Application.get().getScreenSize().getWidth();// 屏幕宽度px
//        float leftAndRighPadding = context.getResources().getDimension(R.dimen.dynamic_padding);// 左右边距px
//        float logoSize = context.getResources().getDimension(R.dimen.dynamic_logo_width);// logo大小px
//        float logoMarginImageRight = context.getResources().getDimension(R.dimen.dynamic_logo_margin_grid_image);// logo距离GridView右边大小px
//        float itemPadding = context.getResources().getDimension(R.dimen.dynamic_grid_item_padding);// GridView的item边距右边大小px
//        int imageNum = context.getResources().getInteger(R.integer.words_max_size_dynamic_list_images);// 最多显示几张图片
//        // 屏幕宽度 - 左右边距 - logo大小 - logo距离图片右侧大小-每张图片边距/图片张数
//        return (int) ((screenWid - leftAndRighPadding * 2 - logoSize - logoMarginImageRight) / imageNum - itemPadding);
//    }
//
    public interface SelectImageListener {
        void onSelectDone();

        void onSelectFail();
    }

}
